package com.nobug.service.system;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.nobug.bean.BaseListData;
import com.nobug.bean.system.Storage;
import com.nobug.bean.system.StorageExample;
import com.nobug.mapper.systemMappers.StorageMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
public class StorageServiceImpl implements StorageService {

    @Autowired
    StorageMapper storageMapper;

    @Override
    public BaseListData queryStorageList(Integer page, Integer limit, String key, String name, String sort, String order) {
        PageHelper.startPage(page,limit);
        StorageExample storageExample = new StorageExample();
        storageExample.setOrderByClause(sort + " " + order);
        StorageExample.Criteria criteria = storageExample.createCriteria();
        if(key != null && key != ""){criteria.andKeyLike("%" + key + "%");}
        if(name != null && name != ""){criteria.andNameLike("%" + name + "%");}
        List<Storage> storages = storageMapper.selectByExample(storageExample);
        PageInfo<Storage> storagePageInfo = new PageInfo<>(storages);
        long total = storagePageInfo.getTotal();
        return BaseListData.ok(storages,total);
    }

    @Override
    public Storage updateStorage(Storage storage) {
        Date time= new Date();
        DateFormat df = DateFormat.getDateTimeInstance();
        String timeNow = df.format(time);
        storage.setUpdateTime(timeNow);
        storageMapper.updateByPrimaryKey(storage);
        int id = storage.getId();
        Storage storage4Return = storageMapper.selectByPrimaryKey(id);
        return storage4Return;
    }

    @Override
    public void deleteStorage(Storage storage) {
        int id = storage.getId();
        storageMapper.deleteByPrimaryKey(id);
    }
}
